#include <iostream>
#include <vector>

using namespace std;

struct TreeNode {
    int val;
    TreeNode* left;
    TreeNode* right;
    TreeNode() : val(0), left(nullptr), right(nullptr) {}
    TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
    TreeNode(int x, TreeNode* left, TreeNode* right) : val(x), left(left), right(right) {}
    
};

class Solution1 {
public:
    TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {
        int pos = 0, begin = 0, end = inorder.size() - 1;
        return _buildTree(preorder, inorder, pos, begin, end);
    }

    TreeNode* _buildTree(vector<int>& preorder, vector<int>& inorder, int& pos, int begin, int end)
    {
        if (begin > end)
        {
            --pos;
            return nullptr;
        }

        TreeNode* cur = new TreeNode(preorder[pos]);
        int index = begin;
        while (index <= end)
        {
            if (preorder[pos] == inorder[index])
                break;
            index++;
        }

        cur->left = _buildTree(preorder, inorder, ++pos, begin, index - 1);
        cur->right = _buildTree(preorder, inorder, ++pos, index + 1, end);
        return cur;
    }
};

//int main()
//{
//    vector<int> preorder({ 3,9,20,15,7 });
//    vector<int> inorder({ 9, 3, 15, 20, 7 });
//
//    Solution().buildTree(preorder, inorder);
//    return 0;
//}

////////////////////////////////////////////////////

class Solution2 {
public:
    TreeNode* buildTree(vector<int>& inorder, vector<int>& postorder) {
        int begin = 0, end = postorder.size() - 1;
        int pos = end;
        return _buildTree(inorder, postorder, pos, begin, end);
    }

    TreeNode* _buildTree(vector<int>& inorder, vector<int>& postorder, int& pos, int begin, int end)
    {
        if (begin > end)
        {
            ++pos;
            return nullptr;
        }

        TreeNode* cur = new TreeNode(postorder[pos]);
        int index = begin;
        while (index <= end)
        {
            if (inorder[index] == postorder[pos])
                break;
            index++;
        }

        cur->right = _buildTree(inorder, postorder, --pos, index + 1, end);
        cur->left = _buildTree(inorder, postorder, --pos, begin, index - 1);
        return cur;
    }
};


//////////////////////////////////////
#include <stack>

class Solution {
public:
    vector<int> preorderTraversal(TreeNode* root) {
        vector<int> ans;
        if (root == nullptr)
            return ans;
        stack<TreeNode*> st;
        TreeNode* cur = root;
        while (cur || !st.empty())
        {
            while (cur)
            {
                st.push(cur);
                ans.push_back(cur->val);
                cur = cur->left;
            }
            TreeNode* top = st.top();
            st.pop();
            cur = top->right;
        }

        return ans;
    }
};

//////////////////////////